package com.xiguanlezz.cn.scanner;

import com.xiguanlezz.cn.ScannerConst;
import com.xiguanlezz.cn.annotation.RpcService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author：习惯了种种
 * @CreateDate：2024/11/3 13:36
 * @Description：服务提供者注解扫描器
 */
@Slf4j
public class RpcServiceScanner extends ClassScanner {

    public static Map<String, Object> doScanAndRegisterService(String packageName) {
        Map<String, Object> handlerMap = new HashMap<>();

        try {
            // 扫面指定包名下的类文件。存在下面两种情况
            // 1. packageName就是jar包。形如：jar:http://www.foo.com/bar/baz.jar!/
            // 2. packageName是某个包路径
            List<String> classNameList = getClassNameList(packageName);
            if (CollectionUtils.isEmpty(classNameList)) {
                return handlerMap;
            }

            for (String className : classNameList) {
                Class<?> clazz = Class.forName(className);
                RpcService rpcServiceAnno = clazz.getAnnotation(RpcService.class);
                if (Objects.nonNull(rpcServiceAnno)) {
                    // 服务名优先用注解上的interfaceClass
                    String serviceInterfaceName = Objects.isNull(rpcServiceAnno.interfaceClass())
                            ? className
                            : rpcServiceAnno.interfaceClass().getName();
                    String key = String.format(ScannerConst.SERVICE_KEY_FORMAT, serviceInterfaceName, rpcServiceAnno.version(), rpcServiceAnno.group());
                    // key为服务的唯一标志，value为反射创建的服务提供者对象
                    handlerMap.put(key, clazz.newInstance());
                }
            }
        } catch (ClassNotFoundException | IOException | InstantiationException | IllegalAccessException e) {
            log.warn("doScanAndRegisterService ===> getClassNameList error: {}", e);
        }
        return handlerMap;
    }
}
